<template>
  <div class="text-formatter">
    <el-card class="tool-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>文本格式化工具</h3>
          <p class="card-description">对文本进行各种格式化处理，包括特殊格式转换和文本优化</p>
        </div>
      </template>
      
      <div class="tool-content">
        <div class="content-container">
          <div class="left-panel">
            <div class="options-section">
              <h4 class="section-title">格式化类型</h4>
              <div class="format-options">
                <el-radio-group v-model="selectedFormat">
                  <div class="format-option" v-for="option in formatOptions" :key="option.value">
                    <el-radio :label="option.value">
                      {{ option.label }}
                      <el-tag v-if="advancedFeatures.includes(option.value)" size="small" type="warning">高级</el-tag>
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
            </div>
            
            <div class="settings-section" v-if="selectedFormat === 'convertPunctuation'">
              <h4 class="section-title">标点符号转换设置</h4>
              <div class="settings-options">
                <el-form>
                  <el-form-item>
                    <el-radio v-model="options.convertToChinese" :label="true">转换为中文标点</el-radio>
                  </el-form-item>
                  <el-form-item>
                    <el-radio v-model="options.convertToEnglish" :label="true">转换为英文标点</el-radio>
                  </el-form-item>
                  <el-form-item>
                    <el-radio v-model="options.convertToChinese" :label="false" v-if="!options.convertToEnglish">不转换</el-radio>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            
            <!-- 会员提示 -->
            <div class="pro-tip" v-if="advancedFeatures.includes(selectedFormat) && !canUseCurrentFeature">
              <el-alert
                title="高级功能"
                type="warning"
                description="此功能需要Pro会员才能使用。请登录并升级到Pro会员解锁所有高级功能。"
                show-icon
                :closable="false"
              />
            </div>
          </div>
          
          <div class="right-panel">
            <div class="input-section">
              <h4 class="section-title">输入原始文本</h4>
              <el-input
                v-model="inputText"
                type="textarea"
                :rows="10"
                placeholder="在此输入需要格式化的文本..."
                resize="none"
              ></el-input>
            </div>
            
            <div class="actions-section">
              <el-button type="primary" @click="formatText" :disabled="!inputText || (advancedFeatures.includes(selectedFormat) && !canUseCurrentFeature)">格式化</el-button>
              <el-button type="danger" @click="clearText" :disabled="!inputText">清空</el-button>
            </div>
            
            <div class="result-section" v-if="formattedText">
              <h4 class="section-title">格式化结果</h4>
              <div class="result-container">
                <pre class="result-content">{{ formattedText }}</pre>
              </div>
              <div class="result-actions">
                <el-button type="primary" @click="copyFormattedText">复制结果</el-button>
                <el-button @click="downloadResult" v-if="canDownload">下载结果</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="guide-section">
        <h4 class="section-title">快速使用指南</h4>
        <div class="guide-container">
          <div class="guide-step">
            <div class="step-number">1</div>
            <div class="step-content">
              <p class="step-text">在左侧选择您需要的格式化类型</p>
            </div>
          </div>
          <div class="guide-step">
            <div class="step-number">2</div>
            <div class="step-content">
              <p class="step-text">在文本框中输入或粘贴需要处理的文本</p>
            </div>
          </div>
          <div class="guide-step">
            <div class="step-number">3</div>
            <div class="step-content">
              <p class="step-text">点击"格式化"按钮进行处理</p>
            </div>
          </div>
          <div class="guide-step">
            <div class="step-number">4</div>
            <div class="step-content">
              <p class="step-text">处理完成后，可以复制结果或继续编辑</p>
            </div>
          </div>
        </div>
        <p class="tip-text"><strong>注意：</strong> 标有<el-tag size="small" type="warning">高级</el-tag>的功能需要Pro会员才能使用。</p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
/**
 * 文本格式化工具组件
 * 提供多种文本格式化功能
 */
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

const store = useStore();
const inputText = ref('');
const formattedText = ref('');
const selectedFormat = ref('capitalization');

// 格式化选项
const options = ref({
  removeExtraSpaces: false,
  trimLines: false,
  removeEmptyLines: false,
  mergeParagraphs: false,
  convertToChinese: false,
  convertToEnglish: false
});

// 是否为高级功能（需要PRO会员）
const advancedFeatures = ['markdown', 'removeExtraSpaces', 'convertChineseNums'];

// 检查用户是否可以使用当前功能
const canUseCurrentFeature = computed(() => {
  if (!advancedFeatures.includes(selectedFormat.value)) {
    return true;
  }
  // 检查用户是否为PRO会员
  return store.getters.isProMember || store.getters.hasFreeTrial;
});

// 是否可下载
const canDownload = computed(() => {
  return formattedText.value && formattedText.value.length > 100;
});

// 可用的格式化选项
const formatOptions = [
  { label: '首字母大写', value: 'capitalization' },
  { label: '全部大写', value: 'upperCase' },
  { label: '全部小写', value: 'lowerCase' },
  { label: '句首大写', value: 'sentenceCase' },
  { label: '文本反转', value: 'reverseText' },
  { label: '移除换行', value: 'removeLineBreaks' },
  { label: '移除多余空格', value: 'removeExtraSpaces' },
  { label: '字符统计', value: 'countCharacters' },
  { label: '中文数字转换', value: 'convertChineseNums' },
  { label: '标点符号转换', value: 'convertPunctuation' },
  { label: 'Markdown转纯文本', value: 'markdown' }
];

// 标点符号映射
const punctuationMap = {
  toChinese: {
    '.': '。',
    ',': '，',
    ':': '：',
    ';': '；',
    '?': '？',
    '!': '！',
    '(': '（',
    ')': '）',
    '[': '【',
    ']': '】',
    '"': '"',
    "'": "'"
  },
  toEnglish: {
    '。': '.',
    '，': ',',
    '：': ':',
    '；': ';',
    '？': '?',
    '！': '!',
    '（': '(',
    '）': ')',
    '【': '[',
    '】': ']',
    '\u201c': '"', // 中文左双引号
    '\u201d': '"', // 中文右双引号
    '\u2018': "'", // 中文左单引号
    '\u2019': "'"  // 中文右单引号
  }
};

// 格式化文本
const formatText = () => {
  if (!inputText.value) {
    ElMessage.warning('请先输入文本');
    return;
  }
  
  if (advancedFeatures.includes(selectedFormat.value) && !canUseCurrentFeature.value) {
    ElMessage.warning('此功能需要Pro会员才能使用');
    return;
  }
  
  let result = '';
  
  switch (selectedFormat.value) {
    case 'capitalization':
      result = inputText.value
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
      break;
      
    case 'upperCase':
      result = inputText.value.toUpperCase();
      break;
      
    case 'lowerCase':
      result = inputText.value.toLowerCase();
      break;
      
    case 'sentenceCase':
      result = inputText.value
        .toLowerCase()
        .replace(/(^\s*\w|[.!?]\s*\w)/g, function(c) {
          return c.toUpperCase();
        });
      break;
      
    case 'reverseText':
      result = inputText.value.split('').reverse().join('');
      break;
      
    case 'removeLineBreaks':
      result = inputText.value.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim();
      break;
      
    case 'removeExtraSpaces':
      result = inputText.value.replace(/\s+/g, ' ').trim();
      break;
      
    case 'countCharacters':
      const counts = countCharacters(inputText.value);
      result = `字符总数: ${counts.total}\n`;
      result += `字母: ${counts.letters}\n`;
      result += `数字: ${counts.digits}\n`;
      result += `空格: ${counts.spaces}\n`;
      result += `标点符号: ${counts.punctuation}\n`;
      result += `中文字符: ${counts.chinese}\n`;
      result += `行数: ${counts.lines}`;
      break;
      
    case 'convertPunctuation':
      if (options.value.convertToChinese) {
        result = convertPunctuation(inputText.value, 'toChinese');
      } else if (options.value.convertToEnglish) {
        result = convertPunctuation(inputText.value, 'toEnglish');
      } else {
        result = inputText.value;
      }
      break;
      
    case 'convertChineseNums':
      // 实际实现需要更复杂的逻辑处理中文数字转换
      result = '中文数字转换功能正在开发中...';
      break;
      
    case 'markdown':
      // 实际实现需要引入markdown处理库
      result = '此功能需要集成Markdown解析库，正在施工...';
      break;
      
    default:
      result = inputText.value;
  }
  
  formattedText.value = result;
  
  // 跟踪工具使用
  store.dispatch('trackToolUsage', {
    category: 'text',
    tool: 'formatter',
    subType: selectedFormat.value,
    timestamp: new Date().toISOString()
  });
};

// 统计字符
const countCharacters = (text) => {
  return {
    total: text.length,
    letters: (text.match(/[a-zA-Z]/g) || []).length,
    digits: (text.match(/\d/g) || []).length,
    spaces: (text.match(/\s/g) || []).length,
    punctuation: (text.match(/[.,;:!?()\[\]{}'"]/g) || []).length,
    chinese: (text.match(/[\u4e00-\u9fa5]/g) || []).length,
    lines: (text.match(/\n/g) || []).length + 1
  };
};

// 转换标点符号
const convertPunctuation = (text, mode) => {
  if (!text) return '';
  
  const map = punctuationMap[mode];
  if (!map) return text;
  
  return text.split('').map(char => map[char] || char).join('');
};

// 复制格式化文本
const copyFormattedText = () => {
  if (!formattedText.value) {
    ElMessage.warning('没有可复制的内容');
    return;
  }
  
  navigator.clipboard.writeText(formattedText.value)
    .then(() => {
      ElMessage.success('已复制到剪贴板');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};

// 下载结果
const downloadResult = () => {
  if (!formattedText.value) return;
  
  const blob = new Blob([formattedText.value], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  
  a.href = url;
  a.download = `formatted_text_${new Date().getTime()}.txt`;
  a.style.display = 'none';
  
  document.body.appendChild(a);
  a.click();
  
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  ElMessage.success('文件已下载');
};

// 清空文本
const clearText = () => {
  inputText.value = '';
  formattedText.value = '';
};
</script>

<style scoped>
.text-formatter {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.tool-card {
  border-radius: 8px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.card-header {
  padding-bottom: 15px;
}

.card-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.card-description {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.tool-content {
  padding: 5px 0;
}

.content-container {
  display: flex;
  gap: 20px;
}

.left-panel {
  width: 300px;
  flex-shrink: 0;
}

.right-panel {
  flex: 1;
  min-width: 0;
}

.section-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
  font-weight: 500;
  position: relative;
  padding-left: 12px;
}

.section-title:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #3498db;
  border-radius: 2px;
}

.options-section {
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.format-options {
  margin-top: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.format-option {
  margin-bottom: 12px;
}

.settings-section {
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.settings-options {
  margin-top: 15px;
}

.input-section {
  margin-bottom: 20px;
}

.actions-section {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.result-section {
  margin-bottom: 25px;
}

.result-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  background-color: #f8f9fa;
  max-height: 300px;
  overflow-y: auto;
}

.result-content {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: monospace;
  line-height: 1.6;
}

.result-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.pro-tip {
  margin-bottom: 25px;
}

.guide-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e4e7ed;
}

.guide-container {
  display: flex;
  justify-content: space-between;
  gap: 15px;
  margin-top: 20px;
}

.guide-step {
  flex: 1;
  background-color: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
}

.guide-step:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.step-number {
  width: 32px;
  height: 32px;
  background-color: #3498db;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 12px;
}

.step-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.step-text {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.tip-text {
  font-size: 14px;
  color: #606266;
  margin: 10px 0 0 0;
}

@media (max-width: 768px) {
  .content-container {
    flex-direction: column;
  }
  
  .left-panel {
    width: 100%;
  }
  
  .actions-section {
    flex-wrap: wrap;
  }
  
  .result-section {
    margin-top: 20px;
  }
  
  .guide-container {
    flex-direction: column;
  }
  
  .guide-step {
    flex-direction: row;
    text-align: left;
    padding: 15px;
    margin-bottom: 8px;
  }
  
  .step-number {
    margin-bottom: 0;
    margin-right: 15px;
  }
}
</style> 